package com.bihua.iot.service.impl;

import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bihua.common.core.domain.PageQuery;
import com.bihua.common.core.page.TableDataInfo;
import com.bihua.common.utils.JsonUtils;
import com.bihua.common.utils.StringUtils;
import com.bihua.common.utils.redis.RedisUtils;
import com.bihua.iot.constant.Constants;
import com.bihua.iot.domain.DeviceAction;
import com.bihua.iot.domain.bo.DeviceActionBo;
import com.bihua.iot.domain.vo.DeviceActionVo;
import com.bihua.iot.domain.vo.DeviceVo;
import com.bihua.iot.enums.DeviceConnectStatus;
import com.bihua.iot.mapper.DeviceActionMapper;
import com.bihua.iot.service.IDeviceActionService;
import com.bihua.iot.service.IDeviceService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.RequiredArgsConstructor;

/**
 * 设备动作数据Service业务层处理
 *
 * @author bihua
 * @date 2023-06-16
 */
@RequiredArgsConstructor
@Service
public class DeviceActionServiceImpl implements IDeviceActionService {

    private final DeviceActionMapper baseMapper;
    private final IDeviceService iDeviceService;

    /**
     * 查询设备动作数据
     */
    @Override
    public DeviceActionVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询设备动作数据列表
     */
    @Override
    public TableDataInfo<DeviceActionVo> queryPageList(DeviceActionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DeviceAction> lqw = buildQueryWrapper(bo);
        Page<DeviceActionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询设备动作数据列表
     */
    @Override
    public List<DeviceActionVo> queryList(DeviceActionBo bo) {
        LambdaQueryWrapper<DeviceAction> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DeviceAction> buildQueryWrapper(DeviceActionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DeviceAction> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceIdentification()), DeviceAction::getDeviceIdentification, bo.getDeviceIdentification());
        lqw.eq(StringUtils.isNotBlank(bo.getActionType()), DeviceAction::getActionType, bo.getActionType());
        lqw.eq(StringUtils.isNotBlank(bo.getMessage()), DeviceAction::getMessage, bo.getMessage());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), DeviceAction::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增设备动作数据
     */
    @Override
    public Boolean insertByBo(DeviceActionBo bo) {
        DeviceAction add = BeanUtil.toBean(bo, DeviceAction.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改设备动作数据
     */
    @Override
    public Boolean updateByBo(DeviceActionBo bo) {
        DeviceAction update = BeanUtil.toBean(bo, DeviceAction.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DeviceAction entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除设备动作数据
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void insertEvent(JSONObject thinglinksMessage) {
        Map<String, Object> map = new HashMap<>();
        map = JsonUtils.parseObject(thinglinksMessage.toJSONString(), map.getClass());
        DeviceAction deviceAction = new DeviceAction();
        deviceAction.setDeviceIdentification(String.valueOf(map.get("clientId")));
        deviceAction.setActionType(String.valueOf(map.get("event")));
        deviceAction.setStatus("success");
        deviceAction.setMessage(thinglinksMessage.toJSONString());
        baseMapper.insert(deviceAction);
    }

    @Override
    public void connectEvent(JSONObject thinglinksMessage) {
        Map<String, Object> map = new HashMap<>();
        map = JsonUtils.parseObject(thinglinksMessage.toJSONString(), map.getClass());
        iDeviceService.updateConnectStatusByClientId(DeviceConnectStatus.ONLINE.getValue(), String.valueOf(map.get("clientId")));
    }
    /**
     * 设备断开事件
     *
     * @param thinglinksMessage
     */
    @Override
    public void closeEvent(JSONObject thinglinksMessage) {
        Map<String, Object> map = new HashMap<>();
        map = JsonUtils.parseObject(thinglinksMessage.toJSONString(), map.getClass());
        iDeviceService.updateConnectStatusByClientId(DeviceConnectStatus.OFFLINE.getValue(), String.valueOf(map.get("clientId")));
    }
    /**
     * 刷新设备缓存
     *
     * @param thinglinksMessage
     */
    @Override
    public void refreshDeviceCache(JSONObject thinglinksMessage) {
        Map<String, Object> map = new HashMap<>();
        map = JsonUtils.parseObject(thinglinksMessage.toJSONString(), map.getClass());
        DeviceVo device = iDeviceService.findOneByClientId(String.valueOf(map.get("clientId")));
        if (null != device){
            //缓存设备信息
            RedisUtils.setCacheObject(Constants.DEVICE_RECORD_KEY+device.getClientId(), device, Duration.ofSeconds(60L+ Long.parseLong(RandomUtil.randomNumbers(1))));
        }
    }
}
